package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

@SuppressWarnings("serial")
public class MoneyServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		String money = null;
		String name = req.getParameter("name");
		
		if(name!=null)
		{
			try {
				URL url = new URL("http://www.statmyweb.com/tools/webwort.php");
		        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		        connection.setDoOutput(true);
		        connection.setReadTimeout(500000);
				connection.setConnectTimeout(1000000);
		        connection.setRequestMethod("POST");
		        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
		        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
		        writer.write("domain=" + name);
		        writer.close();
		        String content = "";
		        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
		        	
		        	 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	    			
	    			while(1==1)
	    			{
	    				String str = reader.readLine();
	    				if(str==null) break;
	    				content+=str;
	    				
	    			}
		        }
				Document doc = Jsoup.parse(content);
				money = doc.select("h3").toString();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		req.setAttribute("money", money);
		req.setAttribute("name", name);
		
		try {
			req.getRequestDispatcher("money.jsp").forward(req, resp);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
